#include "queue.h"
#include <stdlib.h>

link_t* new_node(datatype data);

queue_t* InitQueue()
{
	queue_t* queue = (queue_t*)malloc(sizeof(queue_t));
	if (queue == NULL)
		return NULL;
	queue->head = NULL;
	queue->err = NULL;
	queue->size = 0;
	return queue;
}

int PushQueue(queue_t* queue, datatype data)
{
	if (queue == NULL)
		return QUEUEISNULL;
	link_t* node = new_node(data);
	if (node == NULL)
		return MEMORYMALLOCFALSE;
	if (queue->size == 0) {
		queue->head = node;
		queue->err = node;
	} else {
		queue->err->next = node;
		queue->err = node;
	}
	queue->size++;
	return 0;
}

int PopQueue(queue_t* queue, datatype* e)
{
	if (queue == NULL)
		return QUEUEISNULL;
	if (queue->size == 0)
		return QUEUEISNULL;
	link_t* node = queue->head;
	queue->head = queue->head->next;
	if (queue->size == 1)
		queue->err = NULL;
	queue->size--;
	*e = node->data;
	free(node);
	return 0;
}

int Length(queue_t* queue)
{
	if (queue == NULL)
		return QUEUEISNULL;
	return queue->size;
}

void DestroyQueue(queue_t** queue)
{
	if (queue == NULL)
		return;
	if (*queue == NULL)
		return;
	link_t* node;
	while ((*queue)->head != NULL) {
		node = (*queue)->head;
		(*queue)->head = (*queue)->head->next;
		free(node);
		(*queue)->size--;
	}
	(*queue)->err = NULL;
	free((*queue));
	(*queue) = NULL;
}

link_t* new_node(datatype data)
{
	link_t* node = (link_t*)malloc(sizeof(link_t));
	if (node == NULL)
		return NULL;
	node->data = data;
	node->next = NULL;
	return node;
}